<template>
  <div>
    <el-row style="margin-top:20px;">
      <el-col>
        <el-input v-model="searchtext" style="width:200px" clearable placeholder="请输入名称" @keyup.enter.native="handleFilter" @mousedown="handleFilter"/>
        <el-button type="primary" style="margin-left:10px;" @click="handleFilter">搜索</el-button>
        <el-button size="medium" type="info" @click="clearParams">清空</el-button>
      </el-col>
    </el-row>
    <el-row style="margin-top:20px;">
      <el-col :span="4">
        <h4>活动中的会员等级</h4>
      </el-col>
      <el-col :span="2" :offset="18" style="margin-top:13px;">
        <el-button type="primary" @click="addCourseDialog">添加活动会员等级</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData.slice((currentpage-1)*pagesize,currentpage*pagesize)" border style="width: 100%">
      <el-table-column prop="userLevelName" label="名称" width="500" align="center">
        <template slot-scope="scope">
          <a href="javascript:void(0)" style="color:#63B8FF">{{ scope.row.userLevelName }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="300" align="center">
        <template slot="header" slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="价格，并非是成交价格。" placement="top">
            <span>价格<i class="el-icon-question"></i></span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="代理商分成比例" width="300" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.rate }}</span>
          <span>%</span>
        </template>
      </el-table-column>
      <el-table-column prop="manage" label="操作" min-width="40" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="ratioset(scope.row)">比例设置</el-button>
          <el-button type="text" size="small" @click="exitActivity(scope.row)">退出活动</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <!-- 比例设置弹框 -->
    <el-dialog :visible.sync="ratioDialogVisible" title="比例设置" width="30%">
      <div>
        <span>代理商分成比例</span>
        <el-input v-model="updateForm.rate" style="width:300px;"/>
        %
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ratioDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="ratioConfirm">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 海报设置弹框 -->
    <el-dialog :visible.sync="posterDialogVisible" title="海报设置" width="50%">
      <div class="posterBox">
        <el-form v-model="poster" label-width="100px">
          <el-form-item label="背景图片">
            <el-upload
              :on-change="handleChange"
              :http-request="uploadFile"
              :limit="1"
              :show-file-list="false"
              class="upload-demo"
              action=""
              accept="image/jpg,image/gif,image/png"
            >
              <el-button slot="trigger" size="small" type="primary">选择封面</el-button>
              <div slot="tip" class="el-upload__tip">请上传jpg, gif, png格式的图片。</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="二维码图片">
            <el-button size="small" type="primary" @click="createQR">点击生成</el-button>
          </el-form-item>
          <el-form-item label="海报标题">
            <el-input v-model="poster.title" placeholder="请输入标题" style="width:300px"/>
          </el-form-item>
          <el-form-item label="海报简介">
            <el-input
              v-model="poster.description"
              :autosize="{ minRows: 5, maxRows: 5}"
              type="textarea"
              placeholder="请输入班级描述"
              style="width:300px;"
            />
          </el-form-item>
        </el-form>
        <div class="posterImg">
          <img v-if="poster.backImg" :src="poster.backImg" class="posterImg-bg">
          <img v-else src="../../../../../assets/distribution/poster.png" class="posterImg-bg">
          <div class="posterImg-QRcode">
            <canvas id="msg"></canvas>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="posterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="posterConfirm">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 添加活动课程弹框 -->
    <add-course :data="courseDialog" @closed="closeRec" @confirm="confirm"/>
  </div>
</template>
<script>
  import Pagination from '@/components/Pagination' // 分页组件
  import addCourse from './adduserleveldialog.vue'
  import {getTenantId, getUserName} from '@/utils/auth'
  import {addOrUpdateUserLevelSetting, addUserLevelActivity, delUserLevel, getUserLevelActivityList, getUserLevelSetting, updateUserLevelActivity} from '@/api/distribution/userlevelset'
  import {upLoadFile} from '@/api/upLoadFile'
  import QRCode from 'qrcode'

  export default {
    components: {
      addCourse,
      Pagination
    },
    data() {
      return {
        saleCourseSetting: {
          status: false
        },
        searchtext: '',
        total: 0,
        currentpage: 1,
        pagesize: 10,
        tableData: [],
        filterData: [],
        // 添加课程弹框是否显示
        courseDialog: {
          dialog: false
        },
        // 比例设置弹框是否显示
        ratioDialogVisible: false,
        updateForm: {},
        // 海报弹框设置是否显示
        posterDialogVisible: false,
        poster: {
          title: '',
          backImg: ''
        },
        file: ''
      }
    },
    created() {
      this.getStatus();
      this.getData()
    },
    methods: {
      getStatus() {
        getUserLevelSetting(getTenantId()).then(res => {
          if (res.data.item) {
            this.saleCourseSetting = res.data.item
          }
        })
      },
      clearParams() {
        this.searchtext = '';
        this.getData()
      },
      saveStatus() {
        let status = '';
        if (this.saleCourseSetting.status) {
          status = '开启'
        } else {
          status = '关闭'
        }
        if (!this.saleCourseSetting.id) {
          this.saleCourseSetting.creator = getUserName();
          this.saleCourseSetting.tenantId = getTenantId()
        }
        getUserLevelSetting(this.saleCourseSetting).then(() => {
          this.$notify({
            title: '成功',
            message: `成功${status}`,
            type: 'success',
            duration: 2000
          });
          this.getStatus()
        })
      },
      getData() {
        getUserLevelActivityList(getTenantId()).then(res => {
          this.tableData = res.data.items;
          this.filterData = res.data.items;
          this.total = res.data.items.length
        })
      },
      handleFilter() {
        this.tableData = this.filterData.filter(item => {
          if (this.searchtext && item.userLevelName.toLocaleLowerCase().indexOf(this.searchtext.toLocaleLowerCase()) < 0) return false;
          return true
        });
        this.total = this.tableData.length
      },
      // 接收子元素添加课程的数据
      addCourseDialog() {
        this.courseDialog.dialog = true
      },
      closeRec() {
        this.courseDialog = {dialog: false}
      },
      confirm(form) {
        this.courseDialog.dialog = false;
        addUserLevelActivity(form).then(() => {
          this.$notify({
            title: '成功',
            message: `活动课程添加成功`,
            type: 'success',
            duration: 2000
          });
          this.getData()
        })
      },
      // 设置比例事件
      ratioset(row) {
        this.ratioDialogVisible = true;
        this.updateForm = Object.assign({}, row)
      },
      ratioConfirm() {
        this.ratioDialogVisible = false;
        updateUserLevelActivity(this.updateForm).then(() => {
          this.$notify({
            title: '成功',
            message: `成功修改代理商分成比例`,
            type: 'success',
            duration: 2000
          });
          this.getData()
        })
      },
      // 退出活动
      exitActivity(row) {
        this.$confirm('确定将该会员等级退出活动吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUserLevel(row.id).then(() => {
            this.$notify({
              title: '成功',
              message: '成功退出活动',
              type: 'success',
              duration: 2000
            });
            this.getData()
          })
        })
      },
      // 海报设置事件
      posterset(row) {
        this.posterDialogVisible = true;
        this.poster = Object.assign({}, row)
      },
      posterConfirm() {
        this.posterDialogVisible = false;
        updateUserLevelActivity(this.poster).then(() => {
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      // 背景图片上传事件
      handleChange(file) {
        this.file = file.raw
      },
      uploadFile() {
        const fileForm = new FormData();
        fileForm.append('name', this.file.name);
        fileForm.append('uid', this.file.uid);
        fileForm.append('file', this.file);
        upLoadFile(fileForm).then(response => {
          this.poster.backImg = response.data.url
        })
      },
      createQR() {
        const msg = document.getElementById('msg');
        const val = this.poster.qrCode;
        QRCode.toCanvas(msg, val, function (error) {
          console.log(error)
        })
      },
      QRCode() {
        new QRCode('qrcode', {
          width: 100,
          height: 100, // 高度
          text: '56663159' // 二维码内容
          // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
          // background: '#f0f'
          // foreground: '#ff0'
        })
      },
      handleSizeChange(val) {
        this.currentpage = 1;
        this.pagesize = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        this.currentpage = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      }
    }
  }
</script>
<style lang="scss">
  .overall-title {
    background-color: #ccc;
    padding: 20px;

    p {
      font-size: 14px;
    }
  }

  // switch文字定位设置
  .switchTops {
    margin-top: 30px;
  }

  .switchStyle .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
  }

  .switchStyle .el-switch__label--left {
    z-index: 9;
    left: 18px;
  }

  .switchStyle .el-switch__label--right {
    z-index: 9;
    left: -5px;
  }

  .switchStyle .el-switch__label.is-active {
    display: block;
  }

  .switchStyle.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 66px !important;
  }

  // 海报弹框样式设置
  .posterBox {
    position: relative;
    width: 100%;

    .posterImg {
      position: absolute;
      top: 0;
      right: 50px;
      width: 220px;
      height: 340px;

      .posterImg-bg {
        width: 100%;
        height: 100%;
      }

      .posterImg-QRcode {
        position: absolute;
        top: 160px;
        right: 60px;
        width: 100px;
        height: 100px;

        #msg {
          width: 100px !important;
          height: 100px !important;
        }
      }
    }
  }
</style>
